import 'dart:async';

import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/check_in_record/record_history/export_excel/select_class_or_department.dart';
import 'package:e_reception_flutter/ui/company/common_person_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/class_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/department_or_class_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/department_or_class_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/department_or_class_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/department_or_class_detail_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/class_or_department/add_or_edit_department_page.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/refresh_company_detail_page_event.dart';
import 'package:e_reception_flutter/ui/create_user/edit_user/edit_user_page_view_model.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/bean/user_select_sort_save_response_bean.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_stream_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'class_or_department_admin_detail.dart';
import 'class_or_department_detail.dart';
import 'class_or_department_page.dart';

class ClassOrDepartmentViewModel extends BasePagerViewModel<DepartmentOrClassListItemBean, DepartmentOrClassListResponse> {
  ///页面类型 （部门/班级）
  int type;

  ///是否是编辑部门
  bool isEdit;

  ///编辑部门或班级时的数据
  DepartmentOrClassListItemBean oldBean;

  ///未分配数
  VgStreamController<int> cntStream;

  ///接口操作结果
  VgStreamController<DepartmentOrClassListItemBean> operateResultController;

  ///详情页面数据结果
  VgStreamController<AdminMemberListBean> detailValueStream;

  /// 今日刷脸人数
  ValueNotifier<int> todayFaceCnt;
  String keyword;

  factory ClassOrDepartmentViewModel(BaseState state) {
    if (state is ClassOrDepartmentPageState) {
      return ClassOrDepartmentViewModel.listPage(state);
    }
    if (state is SelectClassOrDepartmentState) {
      return ClassOrDepartmentViewModel.selectPage(state);
    }
    if (state is AddOrEditClassDepartmentPageState) {
      return ClassOrDepartmentViewModel.addOrEditPage(state);
    }
    if (state is ClassOrDepartmentDetailState) {
      return ClassOrDepartmentViewModel.detailPage(state);
    }
    if (state is ClassOrDepartmentAdminDetailState) {
      return ClassOrDepartmentViewModel.detailAdminPage(state);
    }
    return null;
  }

  ///班级/部门列表页面
  ClassOrDepartmentViewModel.listPage(ClassOrDepartmentPageState state)
      : super(state) {
    type = state.widget.type;
    operateResultController = newAutoReleaseBroadcast();
    cntStream = newAutoReleaseBroadcast();
  }

  ///选择班级/部门列表页面
  ClassOrDepartmentViewModel.selectPage(SelectClassOrDepartmentState state)
      : super(state) {
    type = state.widget.type;
    operateResultController = newAutoReleaseBroadcast();
    cntStream = newAutoReleaseBroadcast();
  }

  ///班级/部门 添加页面
  ClassOrDepartmentViewModel.addOrEditPage(
      AddOrEditClassDepartmentPageState state)
      : super(state) {
    type = state.widget.type;
    isEdit = state.widget.isEdit;
    oldBean = state.widget.oldBean;
    operateResultController = newAutoReleaseBroadcast();
  }

  ///班级/部门 详情页面
  ClassOrDepartmentViewModel.detailPage(ClassOrDepartmentDetailState state)
      : super(state) {
    type = state.widget.type;
    detailValueStream = newAutoReleaseBroadcast();
    todayFaceCnt = ValueNotifier(0);
    operateResultController = newAutoReleaseBroadcast();
  }

  ///班级/部门 详情管理员页面
  ClassOrDepartmentViewModel.detailAdminPage(
      ClassOrDepartmentAdminDetailState state)
      : super(state) {
    type = state.widget.type;
    detailValueStream = newAutoReleaseBroadcast();
    operateResultController = newAutoReleaseBroadcast();
  }

  @override
  void onDisposed() {
    todayFaceCnt?.dispose();
    super.onDisposed();
  }

  // ///列表数据
  // void getData() {
  //   //   type(00部门 01班级)
  //   Map<String, dynamic> params = {
  //     'authId': UserRepository.getInstance().authId,
  //     "current": 1,
  //     "size": '1000',
  //     "type": type == ClassOrDepartmentPage.TYPE_DEPARTMENT ? '00' : '01',
  //     "searchName": keyword ?? ''
  //   };
  //   loading(false);
  //   VgHttpUtils.post(NetApi.DEPARTMENT_OR_CLASS_LIST,
  //       params: params,
  //       callback: BaseCallback(onSuccess: (jsonMap) {
  //         List<ClassOrDepartmentPageBean> result = List();
  //         if (jsonMap != null) {
  //           if (type == ClassOrDepartmentPage.TYPE_DEPARTMENT) {
  //             DepartmentListResponse response =
  //                 DepartmentListResponse.fromMap(jsonMap);
  //             cntStream.add(response?.data?.noDepartmentCnt);
  //             if (response?.data?.page?.records != null) {
  //               result = response.data.page.records
  //                   .map((e) => ClassOrDepartmentPageBean(
  //                       name: e.department,
  //                       adminName: e.adminName,
  //                       adminCnt: e.adminCnt,
  //                       memberCnt: e.memberCnt,
  //                       id: e.departmentid,
  //                       faceCnt: e.faceCnt,
  //                       picurls: e.picurls,
  //                       dpPicurl: e.dpPicurl,
  //                       type: type))
  //                   .toList();
  //             }
  //           }
  //
  //           if (type == ClassOrDepartmentPage.TYPE_CLASS) {
  //             ClassListResponse response = ClassListResponse.fromMap(jsonMap);
  //             cntStream.add(response?.data?.noClassCnt);
  //
  //             if (response?.data?.page?.records != null) {
  //               result = response.data.page.records
  //                   .map((e) => ClassOrDepartmentPageBean(
  //                       name: e.classname,
  //                       adminName: e.adminName,
  //                       adminCnt: e.adminCnt,
  //                       memberCnt: e.memberCnt,
  //                       id: e.classid,
  //                       faceCnt: e.faceCnt,
  //                       type: type,
  //                       picurls: e.picurls,
  //                 dpPicurl: e.dpPicurl,
  //               ))
  //                   .toList();
  //             }
  //           }
  //         }
  //         valueStream.add(result);
  //       }, onError: (e) {
  //         toast(e);
  //         valueStream.add(null);
  //       }));
  // }

  ///保存部门
  void saveDepartment(String departmentName) {
    if (departmentName == null || departmentName.isEmpty) {
      toast("部门名称不能为空");
      return;
    }
    loading(true, msg: "保存中");
    VgHttpUtils.post(ServerApi.BASE_URL + "app/appAddChooseInfo",
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "name": departmentName?.trim() ?? "",
          "type": "00",
        },
        callback: BaseCallback(onSuccess: (dynamic val) {
          loading(false);
          if (val == null) {
            return;
          }
          UserSelectSortSaveResponseBean successBean =
              UserSelectSortSaveResponseBean.fromMap(val);
          if (successBean == null ||
              successBean.data == null ||
              successBean.data.isEmpty) {
            return;
          }
          DepartmentOrClassListItemBean departmentListItemBean =
              new DepartmentOrClassListItemBean();

          successBean.data.forEach((element) {
            // print("gz:::${element.id}:::${element.name}");
            if (element?.name != null &&
                element?.name != "" &&
                element?.name == departmentName) {
              departmentListItemBean.departmentid = element.id;
            }
          });
          departmentListItemBean.department = departmentName;
          departmentListItemBean.type = ClassOrDepartmentPage.TYPE_DEPARTMENT;
          departmentListItemBean.adminCnt = 0;
          departmentListItemBean.memberCnt = 0;
          //保存成功后刷新企业详情
          VgEventBus.global.send(RefreshCompanyDetailPageEvent(msg: '新增部门'));
          operateResultController.add(departmentListItemBean);
          // _pop(DepartmentListItemBean()..id = successBean.data..name = departmentName);
        }, onError: (String msg) {
          loading(false);
          toast(msg);
          operateResultController.add(null);
        }));
  }

  ///保存班级
  void saveClass(String className) {
    if (className == null || className.isEmpty) {
      toast("名称不能为空");
      return;
    }
    loading(true, msg: "保存中");
    VgHttpUtils.post(ServerApi.BASE_URL + "app/appAddChooseInfo",
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "name": className?.trim() ?? "",
          "type": "03",
        },
        callback: BaseCallback(onSuccess: (dynamic val) {
          loading(false);
          if (val == null) {
            return;
          }
          UserSelectSortSaveResponseBean successBean =
              UserSelectSortSaveResponseBean.fromMap(val);
          if (successBean == null ||
              successBean.data == null ||
              successBean.data.isEmpty) {
            return;
          }
          DepartmentOrClassListItemBean addBean = new DepartmentOrClassListItemBean();

          successBean.data.forEach((element) {
            // print("gz:::${element.id}:::${element.name}");
            if (element?.name != null &&
                element?.name != "" &&
                element?.name == className) {
              addBean.classid = element.id;
            }
          });
          addBean.classname = className;
          addBean.type = ClassOrDepartmentPage.TYPE_CLASS;
          addBean.adminCnt = 0;
          addBean.memberCnt = 0;
          operateResultController.add(addBean);
          //保存成功后刷新企业详情
          VgEventBus.global.send(RefreshCompanyDetailPageEvent(msg: '新增班级'));
          // _pop(DepartmentListItemBean()..id = successBean.data..name = departmentName);
        }, onError: (String msg) {
          toast(msg);
          loading(false);
          operateResultController.add(null);
        }));
  }

  ///编辑部门
  void editDepartment(String departmentName, String id, String oldName) {
    if (departmentName == null || departmentName.isEmpty) {
      toast("部门名称不能为空");
      return;
    }
    if (departmentName == oldName) {
      VgEventBus.global.send(RefreshCompanyDetailPageEvent(msg: '编辑部门'));
      oldBean.department = departmentName;
      operateResultController.add(oldBean);
      return;
    }
    loading(true, msg: "保存中");
    HttpUtils.post(
        url:ServerApi.BASE_URL + "app/appUpdateDepartmentClass",
        query: {
          "authId": UserRepository.getInstance().authId ?? "",
          "departmentid": id,
          "department": departmentName?.trim() ?? "",
          "classname": '',
          "classid": '',
          "type": "00",
        }).then((value) {
      loading(false);
      if (value != null) {
        BaseResponseBean responseBean = BaseResponseBean.fromMap(value.data);
        if (responseBean.success) {
          oldBean.department = departmentName;
          operateResultController.add(oldBean);
          return;
        }else{
          toast(responseBean.msg);
        }
      }

      operateResultController.add(null);
    });
  }

  ///编辑班级
  void editClass(String className, String id, String oldName) {
    if (className == null || className.isEmpty) {
      toast("名称不能为空");
      return;
    }
    if (className == oldName) {
      oldBean.classname = className;
      operateResultController.add(oldBean);
      return;
    }
    loading(true, msg: "保存中");
    HttpUtils.post(
      url:ServerApi.BASE_URL + "app/appUpdateDepartmentClass",
      query: {
        "authId": UserRepository.getInstance().authId ?? "",
        "departmentid": '',
        "department": "",
        "classname": className?.trim() ?? '',
        "classid": id,
        "type": "01",
      },
    ).then((value) {
      loading(false);
      if (value != null) {
        BaseResponseBean responseBean = BaseResponseBean.fromMap(value.data);
        if (responseBean.success) {
          oldBean.classname = className;
          operateResultController.add(oldBean);
          return;
        }else{
          toast(responseBean.msg);
        }
      }

      operateResultController.add(null);
    });
  }

  ///保存部门或班级
  void save(String inputText) {
    if (isEdit ?? false) {
      if (oldBean == null) {
        return;
      }
      if (type == ClassOrDepartmentPage.TYPE_DEPARTMENT) {
        editDepartment(inputText, oldBean.departmentid, oldBean.department);
      } else {
        editClass(inputText, oldBean.classid, oldBean.classname);
      }
    } else {
      if (type == ClassOrDepartmentPage.TYPE_DEPARTMENT) {
        saveDepartment(inputText);
      } else {
        saveClass(inputText);
      }
    }
  }

  ///班级/部门详情
  void getDetail(String id) {
    if (StringUtils.isEmpty(id)) {
      toast('数据异常！');
      return;
    }

    Map<String, dynamic> params = {
      'authId': UserRepository.getInstance().authId,
      "type": type == ClassOrDepartmentPage.TYPE_DEPARTMENT ? '00' : '01',
      'classid': type == ClassOrDepartmentPage.TYPE_DEPARTMENT ? '' : id,
      'departmentid': type == ClassOrDepartmentPage.TYPE_DEPARTMENT ? id : '',
    };
    VgHttpUtils.post(NetApi.DEPARTMENT_OR_CLASS_DETAIL,
        params: params,
        callback: BaseCallback(onSuccess: (jsonMap) {
          AdminMemberListBean result;
          if (jsonMap != null) {
            DepartmentOrClassDetailResponse response =
                DepartmentOrClassDetailResponse.fromMap(jsonMap);
            result = response.data;
          }
          detailValueStream.add(result);
          todayFaceCnt?.value = result.todayFaceCnt;
        }, onError: (error) {
          // AdminMemberListBean fake=AdminMemberListBean();
          // fake.adminList=List.generate(4, (index) => CommonPersonBean.fake());
          // fake.memberList=List.generate(10, (index) => CommonPersonBean.fake());
          // detailValueStream.add(fake);
          detailValueStream.add(null);
          toast(error);
        }));
  }

  ///删除
  void delete(DepartmentOrClassListItemBean item, BaseCallback callback) {
    loading(true, msg: "正在删除");
    VgHttpUtils.post(ServerApi.BASE_URL + "app/appDleDepartmentClass",
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "departmentid": item.isDepartment() ? item.departmentid : '',
          "department": item.isDepartment() ? item.department : '',
          "classname": item.isClass() ? item.classname : '',
          "classid": item.isClass() ? item.classid : '',
          "type": item.isDepartment() ? "00" : '01',
        },
        callback: callback);
  }

  ///班级部门移除管理员
  void deleteAdmin(
      DepartmentOrClassListItemBean oldBean, String userid, BaseCallback callback) {
    loading(true, msg: "正在移除");
    VgHttpUtils.post(ServerApi.BASE_URL + "app/appPDRemoveAdmin",
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "id": oldBean.getId() ?? '',
          "type": oldBean.isDepartment() ? "00" : '01',
          "userid": userid
        },
        callback: callback);
  }

  //删除用户
  void deleteUser(BuildContext context,
      {String fuid, String roleid, String userid,String pages}) {
    if (StringUtils.isEmpty(fuid)) {
      VgToastUtils.toast(context, "人员获取信息错误");
      return;
    }
    if (StringUtils.isEmpty(roleid)) {
      VgToastUtils.toast(context, "身份错误");
      return;
    }
    VgHudUtils.show(context, "删除中");
    VgHttpUtils.get(EditUserPageViewModel.DELETE_USER_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "fuid": fuid ?? "",
          "roleid": roleid ?? "",
          "userid": userid ?? ""
        },
        callback: BaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "删除成功");
          VgEventBus.global.send(new ArtificialAttendanceUpdateEvent());//根更新主页管理数
          //更新企业主页数
          VgEventBus.global.send(CompanyNumBarEventMonitor());
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }));
  }

  @override
  String getBodyData(int page) {
    return null;
  }

  @override
  Map<String, dynamic> getQuery(int page) {
    Map<String, dynamic> params = {
      'authId': UserRepository.getInstance().authId,
      "current": page??1,
      "size": 20,
      "type": type == ClassOrDepartmentPage.TYPE_DEPARTMENT ? '00' : '01',
      "searchName": keyword ?? ''
    };
    return params;
  }

  @override
  String getRequestMethod() {
    return HttpUtils.POST;
  }

  @override
  String getUrl() {
    return NetApi.DEPARTMENT_OR_CLASS_LIST;
  }

  @override
  bool isNeedCache() {
    return true;
  }

  @override
  String getCacheKey() {
    return getUrl() + UserRepository.getInstance().getCompanyId();
  }

  @override
  DepartmentOrClassListResponse parseData(VgHttpResponse resp) {
    DepartmentOrClassListResponse vo = DepartmentOrClassListResponse.fromMap(resp?.data, type);
    loading(false);
    cntStream.add(vo?.data?.noDepartmentCnt);
    return vo;
  }
}

// ///班级或部门页面显示数据类型
// class ClassOrDepartmentPageBean {
//   /// 部门/班级名
//   String name;
//
//   ///部门管理员名
//   String adminName;
//
//   ///部门管理员人数
//   int adminCnt;
//
//   ///成员数
//   int memberCnt;
//
//   ///今日刷脸人数
//   int faceCnt;
//   String id;
//
//   ///页面类型[]
//   int type;
//
//   ///头像信息逗号拼接
//   String picurls;
//
//   ///无需拼接的头像
//   String dpPicurl;
//
//   ///是班级数据
//   bool isClass() => ClassOrDepartmentPage.TYPE_CLASS == type;
//
//   ///是部门数据
//   bool isDepartment() => ClassOrDepartmentPage.TYPE_DEPARTMENT == type;
//
//   ClassOrDepartmentPageBean(
//       {this.name,
//       this.adminName,
//       this.adminCnt,
//       this.memberCnt,
//       this.id,
//       this.type,
//       this.faceCnt,
//       this.picurls,
//         this.dpPicurl,
//       });
// }
